<template>
    <!-- 头部标题 -->
    <div class="chat-header">
        <span class="chat-header-title">老朋友</span>
        <User1Icon class="icon-user" @click="onMyPage" />
    </div>
    <div class="chat-container">
        <!-- 聊天消息列表 -->
        <div scroll-y class="message-list" ref="messageListRef">
            <div v-for="(msg, index) in messages" :key="msg.id"
                :class="['message', msg.type === 'user' ? 'user-message' : 'bot-message']">
                <text class="message-content">{{ msg.content }}</text>
                <div class="icon-box" v-if="index>0&&msg.type=='bot'">
                    <div class="icon-sound-box" @click="playAudio(msg.content,index)">
                        <SoundLowIcon class="icon-sound" :style="{opacity:isShowPaly?1:0,zIndex: 1}" />
                        <SoundIcon  class="icon-sound"/>
                        <SoundHighIcon class="icon-sound" />
                        <img class="icon-sound-play" :class="{isShowPaly: isShowPaly&&curIndex==index}" src="../../assets/audio-play.gif" alt="">
                    </div>
                    <FileCopyIcon class="icon-copy" @click="onCopy(msg.content)" />
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
            <t-input placeholder="输入消息..." v-model="newMessage" @keyup.enter="sendMessage" />
            <button @click="sendMessage">发送</button>
        </div>
    </div>
</template>

<script setup>
import { ref, nextTick, watch } from 'vue';
import { chatApi } from "@/api/home"
import { Toast } from 'tdesign-mobile-vue';
import { User1Icon,SoundLowIcon,FileCopyIcon,SoundIcon,SoundHighIcon } from "tdesign-icons-vue-next"
import { useRouter } from 'vue-router';
const router = useRouter();
import { voicePlay } from '@/utils/voicePlay';
import request  from "@/utils/request"


// 跳转到我的页面
const onMyPage = () => {
    router.push("/my")
}


// 消息列表引用
const messageListRef = ref(null);

// 消息列表
const messages = ref([
    { id: 1, type: 'bot', content: '朋友！有什么可以帮你的吗？' },
    // 更多初始消息...
]);

// 新消息输入
const newMessage = ref('');
const preEventSource = ref(null)
// 发送消息函数
const sendMessage = async () => {
    if (newMessage.value.trim() === '') {
        return Toast({
            theme: "warning",
            message: "请输入消息！"
        })
    };
    // 添加一条询问消息
    const newMsg = {
        id: messages.value.length + 1,
        type: "user",
        content: newMessage.value.trim(),
    };

    messages.value.push(newMsg);
    let msg = newMessage.value.trim(); // 保存当前发送的消息
    newMessage.value = '';

    // 开始发送消息给ai大模型
    const loading = Toast({
        theme: 'loading',
        message: '正在思考中...',
        duration: 0
    });
    // 流式数据
    // 关闭上次的链接 防止消息错乱
    preEventSource.value && preEventSource.value.close()
    const evtSource = new EventSource(request.defaults.baseURL+"/stream/chat?msg="+encodeURIComponent(msg))
    let content = "";
    const id = messages.value.length + 1
    evtSource.addEventListener("message", (e)=>{
        const res = JSON.parse(e.data)
        
        preEventSource.value = evtSource

        if(res){
            console.log(93333,res.FinishReason)
            if(res.FinishReason === "stop"){
                // 关闭链接
                evtSource.close()
                return
            }
            content+=res.Delta.Content
            const index = messages.value.findIndex(item=>item.id===id)
            if(index===-1){
                // 关闭加载条
                loading&&loading.clear()
                // 第一次接收数据push
                const botMsg = {
                    id,
                    type: 'bot',
                    content,
                };
                messages.value.push(botMsg);
            }else{
                // 更新数据
                messages.value[index].content = content
            }
        }else{
            // 关闭加载条
            loading&&loading.clear()
            const botMsg = {
                id: messages.value.length + 1,
                type: 'bot',
                content: '抱歉，我暂时无法回答这个问题。',
            };
            messages.value.push(botMsg);
        }

        // 自动滚动到最新消息
        nextTick(() => {
            messageListRef.value.scrollTo({
                top: messageListRef.value.scrollHeight,
                behavior: 'smooth',
            });
        });
    })

};

// 实现一键复制功能
const onCopy = (msg) => {
    const textarea = document.createElement('textarea');
    textarea.value = msg;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    Toast({
        theme: "success",
        message: "消息已复制！"
    });

}


// 播放语音
const isShowPaly  = ref(false)
const curIndex = ref(0) // 保存当前用户点击的按钮对应的数据下标值
const playAudio = async (msg,index)=>{
    curIndex.value = index
    const {synth,utterThis} = voicePlay(msg,()=>{
        // console.log('开始播放')
        isShowPaly.value = true
    },()=>{
        // console.log('结束播放')
        isShowPaly.value = false
    })
    if(synth.speaking){
        // 停止播放
        synth.cancel()
        isShowPaly.value = false
    }else{
        // 重新播放
        synth.speak(utterThis)
    }
    
}

// 监听消息列表变化并缓存数据到本地
watch(messages, (newVal) => {
    localStorage.setItem('ai-chat-assistant-messages', JSON.stringify(newVal));
}, {
    deep: true
});


</script>

<style lang="scss" scoped>
.chat-header {
    height: 50px;
    padding: 10px;
    background-color: #07c160;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 20px;
    position: relative;
    .icon-user {
        position: absolute;
        right: 10px;
        font-size: 23px;
    }
}
.chat-container {
    height: calc(100vh - 50px);
    display: flex;
    flex-direction: column;
}

.message-list {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
}

.message {
    max-width: 70%;
    margin: 5px;
    margin-bottom: 20px;
    padding: 10px 20px;
    border-radius: 20px;
    position: relative;
    .icon-box {
        position: absolute;
        bottom: -25px;
        display: flex;
        .icon-sound-box {
            position: relative;
            margin-right: 35px;
            .icon-sound {
                position: absolute;
                opacity: 0;
                transition: 1s;
            }
            .icon-sound:nth-child(2){
                opacity: 1;
            }
            .icon-sound-play {
                position: absolute;
                width: 36px;
                top: -8px;
                display: none;
            }
            .isShowPaly {
                display: block;
            }
        }
    }
}

.user-message {
    align-self: flex-end;
    background-color: #07c160;
    color: white;
}

.bot-message {
    align-self: flex-start;
    background-color: #f0f0f0;
}

.input-area {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ddd;
}

.input-area input {
    flex: 1;
    margin-right: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.input-area button {
    padding: 10px 20px;
    border: none;
    background-color: #07c160;
    color: white;
    border-radius: 5px;
}
</style>
